<?php

class UcenterController extends BaseController{

    public function init(){
        parent::init();
        if(!$this->member['member_id']){
            if(IS_AJAX){
                $this->ajaxReturn(array('err'=>1,'msg'=>'对不起，你还没登录'));
            }else{
                $this->error('对不起，你还没登录');
            }
        }
    }

    //个人交易币
    public function get_currencyAction(){
        $pageSize = 6;
        $CurrencyModel = new CurrencyModel();
        $MemberModel = new MemberModel();
        $CurrencyUserModel = new Model('CurrencyUser');
        $hidden_empty_currency = $MemberModel->get_field($this->member['member_id'],'hidden_empty_currency');
        $where['member_id'] = $this->member['member_id'];
        if($hidden_empty_currency>0){
            $where['_string'] = ' (`num`<>0 or `forzen_num`<>0) ';
        }
        $count      = $CurrencyUserModel->where($where)->count();// 查询满足要求的总记录数
        $Page       = new Page($count,$pageSize,$this->_request->getParams());
        $Page->setConfig('theme','<div class="page no-margin pull-right">%UP_PAGE% %FIRST% %LINK_PAGE% %END% %DOWN_PAGE%</div>');
        $Page->setConfig('next','»');
        $Page->setConfig('prev','«');
        $Page->setConfig('header','');
        $show       = $Page->show();// 分页显示输出
        $list = $CurrencyUserModel->where($where)
                    ->field('cu_id,currency_id,num,forzen_num,out_url,in_url')
                    ->limit($Page->firstRow.','.$Page->listRows)
                    ->order('cu_id desc')
                    ->select();
        foreach ($list as $key => $value) {
            $currency = $CurrencyModel->currency_one($value['currency_id'],'currency_name,currency_mark');
            $list[$key]['currency_name'] = $currency['currency_name'];
            $list[$key]['currency_mark'] = $currency['currency_mark'];
            $list[$key]['in_href'] = url('set_in_url',array('id'=>$value['cu_id']));
            $list[$key]['out_href'] = url('set_out_url',array('id'=>$value['cu_id']));
            $list[$key]['withdraw_out_href'] = url('withdraw_out',array('currency_id'=>$value['currency_id']));
            $list[$key]['withdraw_out_check'] = url('withdraw_out_check',array('id'=>$value['currency_id']));
        }
        $this->ajaxReturn(array('err'=>0,'list'=>$list,'page'=>$show));
    }

    //获取委托
    public function get_orderAction(){
        $pageSize = 10;
        $currency_id = $this->_request->get('currency_id');
        if(isset($currency_id) && $currency_id!=''){
            $where['currency_id'] = intval($currency_id);
        }
        $trade_status = $this->_request->get('status');
        if(isset($trade_status) && $trade_status=='completed'){
            $where['status'] = array('in',array(2,-1));
        }
        $page_size = $this->_request->get('size');
        if(isset($page_size) && $page_size!=''){
            $pageSize = $page_size;
        }
        $OrdersModel = new OrdersModel();
        $CurrencyModel = new CurrencyModel();
        $where['member_id'] = $this->member['member_id'];
        $count      = $OrdersModel->where($where)->count();// 查询满足要求的总记录数
        $Page       = new Page($count,$pageSize,$this->_request->getParams());
        $Page->setConfig('theme','<div class="page no-margin pull-right">%UP_PAGE% %FIRST% %LINK_PAGE% %END% %DOWN_PAGE%</div>');
        $Page->setConfig('next','»');
        $Page->setConfig('prev','«');
        $Page->setConfig('header','');
        $show       = $Page->show();// 分页显示输出
        $list = $OrdersModel->where($where)
                    ->field('currency_id,currency_trade_id,price,num,trade_num,add_time,type,orders_id,status')
                    ->limit($Page->firstRow.','.$Page->listRows)
                    ->order('add_time desc')
                    ->select();
        foreach ($list as $key => $value) {
            $currency = $CurrencyModel->getCurrencynameById($value['currency_id']);
            $trade_currency = $CurrencyModel->getCurrencynameById($value['currency_trade_id']);
            $list[$key]['currency'] = $currency['currency_mark'];
            $list[$key]['trade_currency'] = $trade_currency['currency_mark'];
            $list[$key]['addtime'] = date('Y-m-d H:i:s',$value['add_time']);
        }
        $this->ajaxReturn(array('err'=>0,'list'=>$list,'page'=>$show));
    }

    //获取交易记录
    public function get_tradeAction(){
        $pageSize = 10;
        $currency_id = $this->_request->get('currency_id');
        if(isset($currency_id) && $currency_id!=''){
            $where['currency_id'] = intval($currency_id);
        }
        $TradeModel = new TradeModel();
        $CurrencyModel = new CurrencyModel();
        $where['member_id'] = $this->member['member_id'];
        $count      = $TradeModel->where($where)->count();// 查询满足要求的总记录数
        $Page       = new Page($count,$pageSize,$this->_request->getParams());
        $Page->setConfig('theme','<div class="page no-margin pull-right">%UP_PAGE% %FIRST% %LINK_PAGE% %END% %DOWN_PAGE%</div>');
        $Page->setConfig('next','»');
        $Page->setConfig('prev','«');
        $Page->setConfig('header','');
        $show       = $Page->show();// 分页显示输出
        $list = $TradeModel->where($where)
                    ->field('currency_id,currency_trade_id,price,num,money,add_time,type')
                    ->limit($Page->firstRow.','.$Page->listRows)
                    ->order('add_time desc')
                    ->select();
        foreach ($list as $key => $value) {
            $currency = $CurrencyModel->getCurrencynameById($value['currency_id']);
            $trade_currency = $CurrencyModel->getCurrencynameById($value['currency_trade_id']);
            $list[$key]['currency'] = $currency['currency_mark'];
            $list[$key]['trade_currency'] = $trade_currency['currency_mark'];
            $list[$key]['addtime'] = date('Y-m-d H:i:s',$value['add_time']);
        }
        $this->ajaxReturn(array('err'=>0,'list'=>$list,'page'=>$show));
    }

    //充值记录
    public function get_payAction(){
        $pageSize = 6;
        $currency_id = $this->_request->get('currency_id');
        if(isset($currency_id) && $currency_id!=''){
            $where['p.currency_id'] = intval($currency_id);
        }
        $PayModel = new PayModel();
        $where['p.member_id'] = $this->member['member_id'];
        $count      = $PayModel
                    ->where($where)
                    ->join('as p left join __CURRENCY__ as c on p.currency_id = c.currency_id')
                    ->count();// 查询满足要求的总记录数
        $Page       = new Page($count,$pageSize,$this->_request->getParams());
        $Page->setConfig('theme','<div class="page no-margin pull-right">%UP_PAGE% %FIRST% %LINK_PAGE% %END% %DOWN_PAGE%</div>');
        $Page->setConfig('next','»');
        $Page->setConfig('prev','«');
        $Page->setConfig('header','');
        $show       = $Page->show();// 分页显示输出
        $list = $PayModel->where($where)
                    ->field('p.add_time,p.num,p.status,c.currency_mark')
                    ->join('as p left join __CURRENCY__ as c on p.currency_id = c.currency_id')
                    ->limit($Page->firstRow.','.$Page->listRows)
                    ->order('p.add_time desc')
                    ->select();
        foreach ($list as $key => $value) {
            $list[$key]['addtime'] = date('Y-m-d H:i:s',$value['add_time']);
        }
        $this->ajaxReturn(array('err'=>0,'list'=>$list,'page'=>$show));
    }

    //提现记录
    public function get_withdrawAction(){
        $pageSize = 6;
        $currency_id = $this->_request->get('currency_id');
        if(isset($currency_id) && $currency_id!=''){
            $where['w.currency_id'] = intval($currency_id);
        }
        $WithdrawModel = new WithdrawModel();
        $where['w.member_id'] = $this->member['member_id'];
        $count      = $WithdrawModel
                    ->where($where)
                    ->join('as w left join __CURRENCY__ as c on w.currency_id = c.currency_id')
                    ->count();// 查询满足要求的总记录数
        $Page       = new Page($count,$pageSize,$this->_request->getParams());
        $Page->setConfig('theme','<div class="page no-margin pull-right">%UP_PAGE% %FIRST% %LINK_PAGE% %END% %DOWN_PAGE%</div>');
        $Page->setConfig('next','»');
        $Page->setConfig('prev','«');
        $Page->setConfig('header','');
        $show       = $Page->show();// 分页显示输出
        $list = $WithdrawModel->where($where)
                    ->field('w.add_time,w.all_num,w.withdraw_fee,w.num,w.status,w.remarks,w.url,c.currency_mark')
                    ->join('as w left join __CURRENCY__ as c on w.currency_id = c.currency_id')
                    ->limit($Page->firstRow.','.$Page->listRows)
                    ->order('w.add_time desc')
                    ->select();
        foreach ($list as $key => $value) {
            $list[$key]['addtime'] = date('Y-m-d H:i:s',$value['add_time']);
        }
        $this->ajaxReturn(array('err'=>0,'list'=>$list,'page'=>$show));
    }

    //添加银行卡
    public function add_cardAction(){
        if(IS_POST){
            $BankModel = new Model('Bank');
            $post = $this->_request->getPost('info');
            $validate = array(
                array('bank_name','require','bank_name>请选择银行'),
                array('card_num','require','card_num>请输入银行卡号'),
                array('card_num',"/^([1-9]{1})(\d{14}|\d{18})$/",'card_num>你的卡号不正确'),
                array('card_name','require','card_name>请填写正确的邮箱号码'),
            );
            $check_result = $BankModel->validate($validate)->create($post);
            if (!$check_result){
                $json=array('err'=>1);
                list($json['key'],$json['msg'])=explode('>',$BankModel->getError());
                $this->ajaxReturn($json);
            }else{
                $post['add_time'] = time();
                $post['member_id'] = $this->member['member_id'];
                $result = $BankModel->add($post);
                if($result){
                    MemberModel::log($this->member['member_id'],$post,1);
                    $this->ajaxReturn(array('err'=>0,'msg'=>'添加成功'));
                }else{
                    MemberModel::log($this->member['member_id'],$post,0);
                    $this->ajaxReturn(array('err'=>1,'msg'=>'添加失败'));
                }
            }
        }
    }

    //绑定google认证
    public function authAction(){
        Yaf\loader::import(APP_PATH.'/common/lib/GoogleAuthenticator.php');//公共方法
        $ga = new PHPGangsta_GoogleAuthenticator();
        if(IS_POST){
            $MemberModel = new MemberModel();
            $sk = $this->_request->getPost('sk');
            $code = $this->_request->getPost('code');
            $checkResult = $ga->verifyCode($sk, $code, 2);
            if ($checkResult) {
                $res = $MemberModel->where(array('member_id'=>$this->member['member_id']))->setField('auth',$sk);
                if($res){
                    $this->ajaxReturn(array('err'=>0,'msg'=>'验证成功'));
                }else{
                    $this->ajaxReturn(array('err'=>1,'msg'=>'验证失败'));
                }
            } else {
                $this->ajaxReturn(array('err'=>1,'msg'=>'验证失败'));
            } 
        }
    }

    //提现
    public function outAction(){
        $BankModel = new Model('Bank');
        $SettingModel = new SettingModel();
        $MemberModel = new MemberModel();
        $WithdrawModel = new WithdrawModel();

        //提现手续费
        $fee = $this->setting['withdraw_fee']?$this->setting['withdraw_fee']:0.1;
        //提现最小总量
        $min_withdraw = $this->setting['min_withdraw_num']?$this->setting['min_withdraw_num']:100;
        //账户余额
        $account = $MemberModel->getUserInfo($this->member['member_id']);
        //绑定的银行卡
        $bank = $BankModel->where(array('member_id'=>$this->member['member_id']))->select();
        if(IS_POST){
            $post = $this->_request->getPost('info');
            $validate = array(
                array('bank_id','require','bank_id>请选择银行卡'),
                array('withdraw_num','require','withdraw_num>请输入你的提现金额'),
            );
            $check_result = $WithdrawModel->validate($validate)->create($post);
            if (!$check_result){
                $json=array('err'=>1);
                list($json['key'],$json['msg'])=explode('>',$WithdrawModel->getError());
                $this->ajaxReturn($json);
            }else{
                if($post['withdraw_num']<$min_withdraw){
                    $this->ajaxReturn(array('err'=>1,'msg'=>'提现金额必须大于等于'.$min_withdraw));
                }
                $result = $WithdrawModel->out($this->member['member_id'],$post['withdraw_num'],$fee,$post['bank_id']);
                if($result){
                    MemberModel::log($this->member['member_id'],$post,1);
                    $this->ajaxReturn(array('err'=>0,'msg'=>'提现成功','url'=>url('ucenter/index')));
                }else{
                    MemberModel::log($this->member['member_id'],$post,0);
                    $this->ajaxReturn(array('err'=>1,'msg'=>'提现失败'));
                }
            }
        }
    }

    /**
     * [get_auth_qrcodeAction google验证二维码]
     * @return [type] [description]
     */
    public function get_auth_qrcodeAction(){
        Yaf\loader::import(APP_PATH.'/common/lib/phpqrcode.php');
        $name = urlencode('HF平台（'.$this->member['email'].'）');
        $sk = $this->_request->get('sk');
        $str = 'otpauth://totp/'.$name.'?secret='.$sk.'';
        QRcode::png($str,false,0,10,2);
    }

    /**
     * [set_out_urlAction 设置提币地址]
     */
    public function set_out_urlAction(){
        if(IS_POST){
            $CurrencyModel = new CurrencyModel();
            $CurrencyUserModel = new Model('CurrencyUser');
            $cu_id = $this->_request->get('id');
            $post['out_url'] = $this->_request->getPost('out_url');
            $validate = array(
                array('out_url','require','out_url>提币钱包地址不能为空'),
            );
            $check_result = $CurrencyUserModel->validate($validate)->create($post);
            if (!$check_result){
                $json=array('err'=>1);
                list($json['key'],$json['msg'])=explode('>',$CurrencyUserModel->getError());
                $this->ajaxReturn($json);
            }else{
                $result = $CurrencyModel->set_out_url($this->member['member_id'],$cu_id,$post['out_url']);
                if($result){
                    MemberModel::log($this->member['member_id'],$post,1);
                    $this->ajaxReturn(array('err'=>0,'msg'=>'地址设置成功','out_url'=>$post['out_url']));
                }else{
                    MemberModel::log($this->member['member_id'],$post,0);
                    $this->ajaxReturn(array('err'=>1,'msg'=>'服务器繁忙，请稍后再试'));
                }
            }
        }
    }
    
    /**
     * [set_in_urlAction 设置转入钱包地址]
     */
    public function set_in_urlAction(){
        if(IS_POST){
            $CurrencyModel = new CurrencyModel();
            $cu_id = $this->_request->get('id');
            $in_url = $CurrencyModel->get_in_url($this->member['member_id'],$cu_id);
            if($in_url){
                $this->ajaxReturn(array('err'=>0,'msg'=>'地址设置成功','in_url'=>$in_url));
            }else{
                $result = $CurrencyModel->set_in_url($this->member['member_id'],$cu_id);
                if($result){
                    MemberModel::log($this->member['member_id'],'设置转入的钱包地址',1);
                    $this->ajaxReturn(array('err'=>0,'msg'=>'地址设置成功','in_url'=>$result));
                }else{
                    MemberModel::log($this->member['member_id'],'设置转入的钱包地址失败',0);
                    $this->ajaxReturn(array('err'=>1,'msg'=>'设置转入的钱包地址失败，请联系管理员'));
                }
            }
            
        }
    }

    /**
     * [withdraw_out_checkAction 检测币是否可以转出]
     * @return [type] [description]
     */
    public function withdraw_out_checkAction(){
        if(IS_POST){
            $CurrencyModel = new CurrencyModel();
            $cu_id = $this->_request->get('id');
            $currency = $CurrencyModel->getCurrencyUser($this->member['member_id'],$cu_id);
            if($currency){
                if($currency['out_url']){
                    $currency['currency'] = $CurrencyModel->getCurrencynameById($currency['currency_id']);
                    $this->ajaxReturn(array('err'=>0,'msg'=>'ok','data'=>$currency));
                }else{
                    $this->ajaxReturn(array('err'=>1,'msg'=>'请设置您提币地址'));
                }
                
            }else{
                $this->ajaxReturn(array('err'=>1,'msg'=>'改币不存在'));
            }
        }
    }

    /**
     * [withdraw_outAction 币种和rmb转出]
     * @return [type] [description]
     */
    public function withdraw_outAction(){
        if(IS_POST){
            Yaf\loader::import(APP_PATH.'/common/lib/GoogleAuthenticator.php');//公共方法
            $ga = new PHPGangsta_GoogleAuthenticator();
            $CurrencyModel = new CurrencyModel();
            $WithdrawModel = new WithdrawModel();
            $post = $this->_request->getPost('info');
            $post['currency_id'] = $this->_request->get('currency_id');
            $my_currency = $CurrencyModel->getCurrencyUser($this->member['member_id'],$post['currency_id']);
            if(!$my_currency['out_url']){
                $this->ajaxReturn(array('err'=>1,'msg'=>'请设置您提币地址'));
            }
            $validate = array(
                array('currency_id','require','currency_id>币种不存在'),
                array('withdraw_num','require','withdraw_num>请输入你的提现金额'),
                array('code','require','code>google验证码不能为空'),
            );
            $check_result = $CurrencyModel->validate($validate)->create($post);
            if (!$check_result){
                $json=array('err'=>1);
                list($json['key'],$json['msg'])=explode('>',$CurrencyModel->getError());
                $this->ajaxReturn($json);
            }else{
                Yaf\loader::import(APP_PATH.'/common/lib/GoogleAuthenticator.php');//公共方法
                $ga = new PHPGangsta_GoogleAuthenticator();
                $checkResult = $ga->verifyCode($this->member['auth'], $post['code'], 2);
                if(!$checkResult){
                    $this->ajaxReturn(array('err'=>1,'msg'=>'google验证码错误'));
                }
                $currency = $CurrencyModel->getCurrencynameById($post['currency_id']);
                if($post['withdraw_num']<$currency['currency_withdraw_min']){
                    $this->ajaxReturn(array('err'=>1,'msg'=>'提现金额必须大于等于'.$currency['currency_withdraw_min']));
                }
                $num = $CurrencyModel->getUserMoney($this->member['member_id'],$post['currency_id'],'num');
                if($post['withdraw_num']>$num){
                    $this->ajaxReturn(array('err'=>1,'msg'=>'账户币不足'));
                }
                $result = $WithdrawModel->out($this->member['member_id'],$post['withdraw_num'],$currency['currency_withdraw_fee'],'',$post['currency_id'],$my_currency['out_url']);
                if($result){
                    MemberModel::log($this->member['member_id'],$post,1);
                    $this->ajaxReturn(array('err'=>0,'msg'=>'提币成功','url'=>url('ucenter/index')));
                }else{
                    MemberModel::log($this->member['member_id'],$post,0);
                    $this->ajaxReturn(array('err'=>1,'msg'=>'提币失败'));
                }
            }
        }
    }

    /**
     * [set_show_empty_currencyAction 设置是否空币种显示]
     */
    public function set_show_empty_currencyAction(){
        if(IS_POST){
            $MemberModel = new MemberModel();
            $show = $this->_request->get('show');
            $post['member_id'] = $this->member['member_id'];
            $post['hidden_empty_currency'] = $show=='on'?1:0;
            $result = $MemberModel->modify($post['member_id'],$post);
            if($result){
                MemberModel::log($this->member['member_id'],$post,1);
                $this->ajaxReturn(array('err'=>0,'msg'=>'设置成功'));
            }else{
                MemberModel::log($this->member['member_id'],$post,0);
                $this->ajaxReturn(array('err'=>1,'msg'=>'服务器繁忙，请稍后再试'));
            }
        }
    }

    /**
     * [personalAction 个人信息]
     * @return [type] [description]
     */
    public function personalAction(){
        if(IS_POST){
            $MemberModel = new MemberModel();
            $post = $this->_request->getPost('info');
            $validate = array(
                array('nick','require','nick>昵称不能为空'),
                array('name','require','name>姓名不能为空'),
                array('birthday','Validate::isBirthDate','birthday>生日不正确',1,'function'),
                array('address','require','address>地址不能为空'),
                array('phone','Validate::isMobilePhone','phone>电话号码不正确',1,'function'),
            );
            $check_result = $MemberModel->validate($validate)->create($post);
            if (!$check_result){
                $json=array('err'=>1);
                list($json['key'],$json['msg'])=explode('>',$MemberModel->getError());
                $this->ajaxReturn($json);
            }else{
                $post['member_id'] = $this->member['member_id'];
                $result = $MemberModel->modify($post['member_id'],$post);
                if($result){
                    MemberModel::log($this->member['member_id'],$post,1);
                    $this->ajaxReturn(array('err'=>0,'msg'=>'设置成功'));
                }else{
                    MemberModel::log($this->member['member_id'],$post,0);
                    $this->ajaxReturn(array('err'=>1,'msg'=>'服务器繁忙，请稍后再试'));
                }
            }
        }
    }

    /**
     * [send_repwd_emailAction 发送修改密码短信]
     * @return [type] [description]
     */
    public function send_repwd_emailAction(){
        if(IS_POST){
            $Rsa = new Rsa();
            $data['code'] = randCode(6,1);
            $data['key'] = 're_pwd';
            $data['time'] = time();
            $code = $Rsa->pubEncrypt(json_encode($data));
            $html=L('re_pwd_html');
            $html = str_replace(array('{1}','{2}','{3}'),array($this->setting['web_title'],$this->member['email'],$data['code']), $html);
            $res = sendMail($this->member['email'],'密码重置',$html,$this->setting);
            if($res){
                Cookie::getInstance()->set(md5('repwd'),$code);
                $this->ajaxReturn(array('err'=>0,'msg'=>'发送成功'));
            }else{
                $this->ajaxReturn(array('err'=>1,'msg'=>'发送失败'));
            }
        }
    }
    /**
     * [change_pwdAction 修改密码]
     * @return [type] [description]
     */
    public function change_pwdAction(){
        if(IS_POST){
            $MemberModel = new MemberModel();
            $Rsa = new Rsa();
            $code = Cookie::getInstance()->get(md5('repwd'));
            $decode = $Rsa->privDecrypt($code);
            $decode = json_decode($decode,true);
            $post = $this->_request->getPost('info');
            $post['checkcode'] =  $decode['code'];
            if(time()-$decode['time']>180){
                $this->ajaxReturn(array('err'=>0,'msg'=>'验证码已过期，请重新发送'));
            }
            $validate = array(
                array('pwd','require','pwd>密码不能为空'),
                array('repwd','pwd','repwd>请输入相同的密码',0,'confirm'),
                array('code','require','code>验证码不能为空'),
                array('checkcode','code','code>验证码不正确',0,'confirm'),
            );
            $check_result = $MemberModel->validate($validate)->create($post);
            if (!$check_result){
                $json=array('err'=>1);
                list($json['key'],$json['msg'])=explode('>',$MemberModel->getError());
                $this->ajaxReturn($json);
            }else{
                $data['member_id'] = $this->member['member_id'];
                $data['pwd'] = encrypt($post['pwd']);
                Cookie::getInstance()->del(md5('repwd'));
                $result = $MemberModel->modify($data['member_id'],$data);
                if($result){
                    MemberModel::log($this->member['member_id'],'修改密码成功',1);
                    $MemberModel->loginOut();
                    $this->ajaxReturn(array('err'=>0,'msg'=>'重置成功'));
                }else{
                    MemberModel::log($this->member['member_id'],'修改密码失败',0);
                    $this->ajaxReturn(array('err'=>1,'msg'=>'服务器繁忙，请稍后再试'));
                }
            }
        }
    }

}